package com.javaweb.dao.impl;

import com.javaweb.dao.TagDao;
import com.javaweb.model.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author HLQ
 * @date 2024/10/21 21:41
 */
@Repository
@Slf4j
public class TagDaoImpl implements TagDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    private RowMapper<Tag> tagRowMapper = new RowMapper<Tag>() {
        @Override
        public Tag mapRow(ResultSet rs, int rowNum) throws SQLException {
            Tag tag = new Tag()
                    .setId(rs.getInt("id"))
                    .setName(rs.getString("name"))
                    .setCreateTime(rs.getTime("create_time"))
                    .setUpdateTime(rs.getTime("update_time"));
            return tag;
        }
    };

    @Override
    public int insert(Tag tag){

        String sql = "INSERT INTO tb_tag (name, create_time, update_time)" +
                "VALUES (?,?,?)";
        Object [] args = new Object[]{
                tag.getName(),
                tag.getCreateTime(),
                tag.getUpdateTime()
        };
        return jdbcTemplate.update(sql,args);
    }

    @Override
    public int insertArticleTag(Integer articleId, Integer[] tagsId){
        int ret = 0;
        String sql = "INSERT INTO tb_article_tag (article_id, tag_id) VALUES (?,?)";
        //创建一个列表来存储每行数据的参数集
        List<Object[]> batchArgs = new ArrayList<>();
        for (int i = 0; i < tagsId.length; i++){
            Object[] args = new Object[]{articleId,tagsId[i]};
            batchArgs.add(args);
        }
        int[] count =  jdbcTemplate.batchUpdate(sql,batchArgs);
        for (int i = 0; i < count.length; i++){
            ret += count[i];
        }
        return ret;
    }
}
